package Demo4.mapper;

import Demo4.pojo.User;
import Demo4.util.IDBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserMapper {
    private IDBUtil dbutil;

    public int insert(User user) {
        try (Connection connection = dbutil.getConnection();) {
            String sql = "insert into user(username,nickname,password,age) " +
                    "values(?,?,?,?)";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getNickname());
            ps.setString(3, user.getPassword());
            ps.setInt(4, user.getAge());
            return ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }

return 0;
    }
public User selectByUsername(String username) {
    try (Connection connection = dbutil.getConnection();) {
        String sql = "SELECT id,username,password, nickname,age" +
                "From user" +
                " WHERE username=?";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1, username);
        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
         /*   User.user=new User();
            User.setId(rs.getInt("id"));
            User.setUsername(rs.getString("username"));
            User.setNickname(rs.getString("nickname"));
            User.setPassword(rs.getString("password"));
            User.setAge(rs.getInt("age"));
            return user;*/
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return null;
}

}
